package com.lcxw.hxzbapi.scheduleTask;

import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbapi.controller.roomcontroller.Qiniu;
import com.lcxw.hxzbapi.controller.roomcontroller.RoomRealization;
import com.lcxw.hxzbapi.entity.pojo.YwpdRoom;
import com.lcxw.hxzbapi.service.YwpdRoomService;
import com.lcxw.hxzbapi.tencentim.common.TencentImRealization;
import java.util.List;
import javax.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class DealRoomExceptionStatus {

    @Resource
    YwpdRoomService ywpdRoomService;

    @Resource
    RoomRealization roomRealization;

    @Resource
    TencentImRealization tencentImRealization;

    @Resource
    Qiniu qiniu;

    /**
     * 每隔30秒清理一次异常 退出的房间状态
     */
    @SneakyThrows
    @Scheduled(cron = "0/30 * * * * ? ")
    void deal() {

        List<YwpdRoom> livingRoomList = null;
        try {
            livingRoomList = ywpdRoomService.selectAllLivingRoom();
        } catch (Exception e) {
            log.error("获取在线房间失败");
        }

        if (livingRoomList != null) {
            for (YwpdRoom ywpdRoom : livingRoomList
            ) {
                Thread thread = new Thread(new DealClass(ywpdRoom));
                thread.start();
            }
        }

    }

    class DealClass implements Runnable {

        YwpdRoom ywpdRoom;

        DealClass(YwpdRoom ywpdRoom) {
            this.ywpdRoom = ywpdRoom;
        }

        @SneakyThrows
        @Override
        public void run() {
            for (int i = 1; i <= 3; i++) {
                try {
                    qiniu.getLiveStatus(ywpdRoom.getRoomId());
                    break;
                } catch (Exception e) {
                    if (i == 3) {
                        ywpdRoom.setLiveStatus(0);
                        try {
                            ywpdRoomService.updateRoom(ywpdRoom);
                        } catch (Exception ex) {
                            log.error("数据库中修改房间状态失败。");
                        }
                        roomRealization.clearRoomCache(ywpdRoom.getRoomId());
                        JSONObject imBody = new JSONObject();
                        imBody.put("GroupId",ywpdRoom.getRoomId()+"");
                        tencentImRealization.destroyGroup(imBody);
                    } else {
                        Thread.sleep(5000);
                    }
                }
            }
        }
    }

}
